package com.darco.darcoapp;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import com.darco.darcoapp.db.DarcoData;

import eneter.messaging.endpoints.typedmessages.TypedResponseReceivedEventArgs;
import DARCOShared.responses.ResponseWrapper;
import DARCOShared.utils.Constants;
import android.os.Bundle;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import static DARCOShared.utils.Constants.*;

public class Visualization_Activity extends MessagingActivity implements OnClickListener{
	private final int CARD_IMAGE_VISUAL_REQUEST=1;
	private final int SEND_CARD_REQUEST=2;
	
	public static final int CARD_SENT =111;
	
	private ContentValues cardInfo=null;
	private ContentValues uniqueInfo=null;
	private ContentValues account=null;
	private ContentValues system=null;
	
	private MessagingManager mm;
	private DarcoData d;
	private Bundle extra=null;
	private String origin=null;	//action to do after the qrscan
	private byte[] cardPreview=null;
	//private byte[] cardImage=null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_visualization_);
		
		findViewById(R.id.visual_locateOwners_button).setOnClickListener(this);

		ImageView preview = (ImageView) findViewById(R.id.visual_card_imageView);
		preview.setOnClickListener(this);
		
		d= new DarcoData(this);
		
		extra=getIntent().getExtras();
		if(extra==null){
			Toast.makeText(this, "error: extras don't found", Toast.LENGTH_SHORT).show();
			return;
		}

		origin=extra.getString(VISUALIZATION_ORIGIN);
		account= (ContentValues) extra.get("account");
		cardInfo= (ContentValues) extra.get("cardInfo");
		uniqueInfo= (ContentValues) extra.get("uniqueInfo");
		system = (ContentValues) extra.get("system");
		

		//visualizzazione informazioni
		if(cardInfo!=null){
			TextView textSN = (TextView) findViewById(R.id.visual_cardSn_textView);
			TextView textID = (TextView) findViewById(R.id.visual_cardId_textView);
			TextView textName = (TextView) findViewById(R.id.visual_cardName_textView);
			TextView textCat = (TextView) findViewById(R.id.visual_cardType_textView);
			TextView textSub = (TextView) findViewById(R.id.visual_cardSubType_textView);
			TextView textActOwn = (TextView) findViewById(R.id.visual_cardOwner_textView);
			TextView textSpecial = (TextView) findViewById(R.id.visual_cardSpecial_textView);
			TextView textStats = (TextView) findViewById(R.id.visual_cardStats_textView);
			TextView textFirstAuth = (TextView) findViewById(R.id.visual_firstAuth_textView);
			TextView textFirstOwn = (TextView) findViewById(R.id.visual_firstOwner_textView);

			//cardImage=cardInfo.getAsByteArray(CARD_IMAGE);
			cardPreview=cardInfo.getAsByteArray(CARD_PREVIEW);

			if(cardPreview!=null){
				Bitmap bmp=BitmapFactory.decodeByteArray(cardPreview,0,cardPreview.length);
				if(bmp!=null){
					preview.setImageBitmap(bmp);
				}
			}
			
			//caricamento dell'immagine da database
			/*if(cardImage==null){
				cardImage= d.getCardImageFromLocalDB(cardInfo.getAsString(CARD_SN));
			}*/
			
			textSN.setText(cardInfo.getAsString(CARD_SN));
			textID.setText(uniqueInfo.getAsString(UNIQUECARD_ID));
			textName.setText(cardInfo.getAsString(CARD_NAME));
			textCat.setText(cardInfo.getAsString(CARD_CATEGORY_NAME));
			textSub.setText(cardInfo.getAsString(CARD_SUBCATEGORY_NAME));
			textSpecial.setText(cardInfo.getAsString(CARD_SPECIAL));

			String statsJ= cardInfo.getAsString(CARD_STATS);
			String stats= new String();
			try {
				JSONObject statsJson= new JSONObject(statsJ);
				Iterator<?> keys = statsJson.keys();

				while( keys.hasNext() ){
					String key = (String)keys.next();
					String value= statsJson.get(key).toString();

					stats+= key+" : "+value+"\n";

				}

				textStats.setText(stats);

			} catch (JSONException e) {
				e.printStackTrace();
				textStats.setText("error in JSON parsing");
			}

			int iscardauth= (int) uniqueInfo.getAsInteger(UNIQUECARD_AUTENTICATED);
			if(iscardauth!=0){
				textActOwn.setText(uniqueInfo.getAsString(UNIQUECARD_ACTUALOWNER));
				textFirstAuth.setText(uniqueInfo.getAsString(UNIQUECARD_FIRSTAUTH));
				textFirstOwn.setText(uniqueInfo.getAsString(UNIQUECARD_ACTUALOWNER));
			}
			else{
				textActOwn.setText("No Actual Owner");
				textFirstAuth.setText("Card Not Authenticated Yet");
				textFirstOwn.setText("No First Owner");
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		extra=getIntent().getExtras();
		if(extra==null){
			Toast.makeText(this, "error: extras don't found", Toast.LENGTH_SHORT).show();
			return false;
		}
		
		String myEmail = ((ContentValues) extra.get("account")).getAsString(ACCOUNT_EMAIL);
		String ownerEmail = ((ContentValues) extra.get("uniqueInfo")).getAsString(UNIQUECARD_ACTUALOWNER);
		if (myEmail.equals(ownerEmail) && extra.getInt(VISUALIZATION_ORIGIN)!=VISUALIZATION_FROM_BT_RECEIVE){
			//sono il proprietario della carta ->applicazione del give(bt)
			getMenuInflater().inflate(R.menu.activity_visualization_owner_, menu);
		}
		else{
			//non sono il proprietario 
			getMenuInflater().inflate(R.menu.activity_visualization_, menu);
		}
		return true;
	}

	@Override
	void onResponseReceived(Object sender,
			TypedResponseReceivedEventArgs<ResponseWrapper> e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()){
		case R.id.visual_card_imageView:
			Intent i1= new Intent(this, Image_Activity.class);
			//i1.putExtra("IMAGE", cardImage);
			i1.putExtra("cardInfo", cardInfo);
			startActivityForResult(i1, 100);
			break;
		case R.id.visual_locateOwners_button :
			Intent i = new Intent(this,CardJourneyActivity.class);
			i.putExtra("mode", Constants.MODE_LOCATE_CARD_OWNERS_NEAR_ME);
			i.putExtra("cardSN", cardInfo.getAsString(CARD_SN));
			i.putExtra("cardUniqueID", uniqueInfo.getAsString(UNIQUECARD_ID));
			i.putExtra("system", system);
			i.putExtra("account", account);
			startActivityForResult(i, 0);
			break;
		}

	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.visual_menu_give:
			Intent i = new Intent(this,BluetoothManager.class);
			i.putExtra("mode", BluetoothManager.INTENT_SCAN_AND_SEND);
			i.putExtra("cardSN", cardInfo.getAsString(CARD_SN));
			i.putExtra("cardUniqueID", uniqueInfo.getAsString(UNIQUECARD_ID));
			i.putExtra("system", system);
			i.putExtra("account", account);
			startActivityForResult(i, SEND_CARD_REQUEST);
			return true;
		case R.id.visual_menu_history:
			Intent i3 = new Intent(this,CardJourneyActivity.class);
			i3.putExtra("system", getIntent().getExtras().getParcelable("system"));
			i3.putExtra("account", getIntent().getExtras().getParcelable("account"));
			i3.putExtra("cardSN", cardInfo.getAsString(CARD_SN));
			i3.putExtra("cardUID", uniqueInfo.getAsString(UNIQUECARD_ID));
			i3.putExtra("mode", Constants.MODE_CARD_JOURNEY);
			startActivityForResult(i3, 0);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==CARD_IMAGE_VISUAL_REQUEST){
			if(resultCode == RESULT_OK){
				//salvo l'immagine nella variabile 
				/*if(cardImage==null){
					cardImage= data.getExtras().getByteArray("IMAGE");
					d.updateCardImageInLocalDB(cardInfo.getAsString(CARD_SN), cardImage);
				}
				*/
						
			}
		}
		if(requestCode == SEND_CARD_REQUEST){
			if(resultCode == BluetoothManager.TRADE_SUCCESSFUL){
				setResult(CARD_SENT);
				finish();
			}
		}
	}
	
	protected void putCardDataIntoLocalDB(){
		//TODO
	}
}


